﻿
var XYH = {};

//#region 常用功能
var MG = (function ($, mg) {
    mg.Ajax = {
        ResultType: {
            Unknow: 510,
            Failure: 511,
            Success: 512
        },
        Run: function (method, params, callback, options, url, keepUrlParams) {
            if (url == undefined || url == null || url == "") {
                url = document.URL;
            }
            var fixedOptions = {
                type: "POST",
                dataType: "JSON",
                success: function (data, status) {
                    if (typeof (callback) == "function") {
                        callback.call(this, data.Type, data.Data, data.Error);
                    }
                }
            };
            if (keepUrlParams) {
                var urlOper = new MG.UrlOper(url);
                urlOper.Set("AccessMode", "Ajax");
                urlOper.Set("Method", method);
                fixedOptions.url = urlOper.Url();
            } else {
                var index = url.indexOf("?");
                if (index > 0) {
                    url = url.substring(0, index);
                }
                fixedOptions.url = url + "?AccessMode=Ajax&Method=" + method;
            }
            if (params != undefined && params != null) {
                if (typeof (params) == "object" && Object.prototype.toString.call(params).toLowerCase() == "[object object]" && !params.length) {
                    fixedOptions.data = params;
                } else {
                    fixedOptions.data = {
                        "data": params
                    };
                }
            }
            if (options == undefined || options == null) {
                options = fixedOptions;
            } else {
                $.extend(options, fixedOptions);
            }
            $.ajax(options);
        }
    };
    mg.PostTo = function (url, data) {
        var form = $("<form method=\"post\" action=\"" + url + "\" style=\"display:none;\"></form>");
        for (var key in data) {
            form.append("<input type=\"text\" name=\"" + key + "\" value=\"" + data[key] + "\">");
        }
        form.appendTo(document.body).submit();
    };
    mg.UrlOper = function (url) {
        this.OriUrl = url || window.location.href;
        this.Href = "";
        this.Params = {};
        this.Jing = "";
        var init = function () {
            var str = this.OriUrl;
            var index = str.indexOf("#");
            if (index > 0) {
                this.Jing = str.substr(index);
                str = str.substring(0, index);
            }
            index = str.indexOf("?");
            if (index > 0) {
                this.Href = str.substring(0, index);
                str = str.substr(index + 1);
                var parts = str.split("&");
                for (var i = 0; i < parts.length; i++) {
                    var kv = parts[i].split("=");
                    this.Params[kv[0].toLowerCase()] = kv[1].toString();
                }
            } else {
                this.Href = this.OriUrl;
                this.Params = {};
            }
        };
        this.Get = function (key) {
            if (key == null) {
                return null;
            }
            return this.Params[key.toLowerCase()];
        };
        this.Set = function (key, val) {
            if (key != null && val != null) {
                this.Params[key.toLowerCase()] = val.toString();
            }
            return this;
        };
        this.Remove = function (key) {
            this.Params[key.toLowerCase()] = undefined;
            return this;
        };
        this.Url = function () {
            var strurl = this.Href;
            var objps = [];
            for (var k in this.Params) {
                if (this.Params[k.toLowerCase()] != null) {
                    objps.push(k.toLowerCase() + "=" + this.Params[k].toString());
                }
            }
            if (objps.length > 0) {
                strurl += "?" + objps.join("&");
            }
            if (this.Jing.length > 0) {
                strurl += this.Jing;
            }
            return strurl;
        };
        init.call(this);
    };
    mg.AddEvent = function (eventName, element, handler) {
        if (element.attachEvent) {
            element.attachEvent("on" + eventName, handler);
        } else {
            element.addEventListener(eventName, handler, false);
        }
    };
    mg.FireEvent = function (handler, sender, args) {
        if (handler != null && $.isFunction(handler)) {
            if (arguments.length > 3) {
                var argArray = new Array();
                for (var i = 2; i < arguments.length; i++) {
                    argArray.push(arguments[i]);
                }
                handler.apply(sender, argArray);
            }
            else {
                handler.call(sender, args);
            }
        }
    };
    mg.ResizeWindow = function (handler, flag) {
        if (flag) {
            handler();
        }

        var fired = false;
        $(window).resize(function () {
            if (!fired) {
                fired = true;
                handler();
                window.setTimeout(function () { fired = false; }, 100);
            }
        });
    };
    mg.PreLoadImage = function (url, callback) {
        var img = new Image();
        img.src = url;
        if (img.complete) {
            callback.call(img);
            return;
        }
        img.onload = function () {
            callback.call(img);
        };
    };
    mg.GetMaxZIndex = function (selector) {
        return Math.max(0, Math.max.apply(null, $.map(((selector || "*") === "*") ? $.makeArray(document.getElementsByTagName("*")) : $(selector),
        function (o) {
            return parseFloat($(o).css("z-index")) || null;
        })));
    };
    mg.SecoudCountDown = function (totalSeconds, onTiming, onCompleted) {
        var _this, _intervalID = null;
        var _seconds, _onTiming, _onCompleted;

        var init = function () {
            if (typeof onTiming !== "function") {
                throw "No Timing Function !";
            }

            _this = this;
            _seconds = totalSeconds;
            _onTiming = onTiming;
            _onCompleted = onCompleted;

            timing();
        };

        var timing = function () {
            if (_seconds > 0) {
                _intervalID = window.setInterval(function () {
                    _seconds--;
                    var totalSeconds = _seconds;
                    _onTiming(Math.floor(totalSeconds / 3600), Math.floor(totalSeconds % 3600 / 60), Math.floor(totalSeconds % 60), _this, totalSeconds);
                    if (_seconds == 0) {
                        window.clearInterval(_intervalID);
                        _intervalID = null;
                        if (typeof _onCompleted === "function") {
                            _onCompleted(_this);
                        }
                    }
                }, 1000);
            }
        };

        this.Stop = function () {
            if (_intervalID != null) {
                window.clearInterval(_intervalID);
                _intervalID = null;
            }
        };

        this.Continue = function () {
            if (_intervalID == null) {
                timing();
            }
        };

        this.Change = function (totalSeconds) {
            this.Stop();

            _seconds = totalSeconds;

            timing();
        };

        init.call(this);
        return this;
    };
    mg.UrlFilter = function (filterMapping, urlOper, pagerParamName) {
        var defaultMapItem = {
            urlParamName: "",
            controlID: "",
            invalidValue: "",
            GetValue: function (id) { return $.trim($("#" + id).val()); },
            SetValue: function (id, value) { $("#" + id).val(value); }
        };
        var pager = pagerParamName || "page_num";
        var urlManager = urlOper || new MG.UrlOper();
        var mapping = createMapping(filterMapping);

        /*#region 私有方法*/
        //创建URL参数/控件映射
        function createMapping(filterMapping) {
            var arr = new Array();
            if (filterMapping) {
                for (var i in filterMapping) {
                    arr.push($.extend({}, defaultMapItem, filterMapping[i]));
                }
            }
            return arr;
        }

        //绑定URL参数值到控件
        function bindToControl(mapItem) {
            var value = urlManager.Get(mapItem.urlParamName);
            if (value) {
                mapItem.SetValue(mapItem.controlID, decodeURIComponent(value));
            }
        };

        //绑定控件值到URL，忽略值无效的控件
        function bindToUrl(mapItem) {
            var value = mapItem.GetValue(mapItem.controlID);
            var equalsValue = mapItem.invalidValue || "";
            if (value == equalsValue) {
                urlManager.Remove(mapItem.urlParamName);
            }
            else {
                urlManager.Set(mapItem.urlParamName, encodeURIComponent(value));

            }
        };

        //判断元素是否存在于数组中
        function contains(arrList, item) {
            for (var i in arrList) {
                if (arrList[i] == item) {
                    return true;
                }
            }
            return false;
        }
        /*#endregion*/

        //添加URL参数/控件映射
        this.AddMapping = function (mapItem) {
            mapping.push($.extend({}, defaultMapItem, mapItem));
        };

        //载入URL参数到控件
        this.Load = function () {
            if (mapping.length > 0) {
                for (var index in mapping) {
                    bindToControl(mapping[index]);
                }
            }
        };

        //根据控件值生成URL参数
        this.Exec = function () {
            if (mapping.length > 0) {
                for (var index in mapping) {
                    bindToUrl(mapping[index]);
                }
                if (pager) {
                    urlManager.Remove(pager);
                }
                location.href = urlManager.Url();
            }
        };

        //自定义参数执行
        this.CustomExec = function (keepParamName) {
            this.Build(keepParamName);

            location.href = urlManager.Url();
        };

        //生成
        this.Build = function (keepParamName) {
            if (mapping.length > 0) {
                var paramList;
                if (keepParamName.indexOf(",") != -1) {
                    paramList = keepParamName.split(",");
                }
                else {
                    paramList = new Array();
                    paramList.push(keepParamName);
                }

                for (var index in mapping) {
                    if (contains(paramList, mapping[index].urlParamName)) {
                        bindToUrl(mapping[index]);
                    }
                    else {
                        urlManager.Remove(mapping[index].urlParamName);
                    }
                }

                if (pager) {
                    urlManager.Remove(pager);
                }
            }
        };

        //获取内部 UrlOper
        this.GetInnerUrlOper = function () {
            return urlManager;
        };

        //清除所有URL参数
        this.Clear = function () {
            if (mapping.length > 0) {
                for (var index in mapping) {
                    urlManager.Remove(mapping[index].urlParamName);
                }
                if (pager != "") {
                    urlManager.Remove(pager);
                }
                location.href = urlManager.Url();
            }
        };

        return this;
    };
    mg.Set = function (text) {
        var _separator = ",";
        var _innerArray = _deserialize(text) || new Array();

        this.Contains = function (item) {
            return _indexOf(item) != -1;
        };

        this.Add = function (item) {
            var index = _indexOf(item);
            if (index != -1) {
                return false;
            }

            _innerArray.push(item);
            return true;
        };

        this.Remove = function (item) {
            var index = _indexOf(item);
            if (index == -1) {
                return false;
            }

            _innerArray.splice(index, 1);
            return true;
        };

        this.Get = function (index) {
            return _innerArray[index];
        };

        this.Count = function () {
            return _innerArray.length;
        };

        this.Join = function (separator) {
            return _innerArray.join(separator);
        };

        this.Serialize = function () {
            return _innerArray.join(_separator);
        };

        function _deserialize(input) {
            if (input != null && input.length > 0) {
                return input.split(_separator);
            }
            return null;
        };

        function _indexOf(item) {
            for (var i in _innerArray) {
                if (_innerArray[i] === item) {
                    return i;
                }
            }
            return -1;
        };

        return this;
    };
    mg.Cookie = {
        Add: function (name, value, expireMinutes, domain, path, isSecure, isHttpOnly) {
            var cookieString = name + "=" + encodeURIComponent(value);

            //默认：会话 Cookie
            if (expireMinutes > 0) {
                var exdate = new Date();
                exdate.setTime(exdate.getTime() + expireMinutes * 60 * 1000);
                cookieString += ";expires=" + exdate.toGMTString();
            }

            //默认：根目录
            if (path == null) {
                path = "/";
            }
            cookieString += ";path=" + path;

            //默认：当前域
            if (domain != null) {
                cookieString += ";domain=" + domain;
            }

            //默认：非安全
            if (isSecure) {
                cookieString += ";Secure";
            }

            //默认：非 HttpOnly
            if (isHttpOnly) {
                cookieString += ";HttpOnly";
            }

            document.cookie = cookieString;
        },
        Get: function (name) {
            if (document.cookie.length > 0) {
                var start = document.cookie.indexOf(name + "=");
                if (start != -1) {
                    start = start + name.length + 1;
                    var end = document.cookie.indexOf(";", start);
                    if (end == -1) {
                        end = document.cookie.length;
                    }
                    return decodeURIComponent(document.cookie.substring(start, end));
                }
            }
            return null;
        },
        Delete: function (name, domain, path) {
            var date = new Date();
            date.setDate(date.getDate() - 1);

            var cookieString = name + "=null;expires=" + date.toGMTString();
            if (path == null) {
                path = "/";
            }
            cookieString += ";path=" + path;

            if (domain != null) {
                cookieString += ";domain=" + domain;
            }
            document.cookie = cookieString;
        }
    };
    mg.IsIE = document.all ? true : false;
    mg.Redirect = function (url) {
        if (mg.IsIE) {
            var referLink = document.createElement('a');
            referLink.href = url;
            document.body.appendChild(referLink);
            referLink.click();
        }
        else {
            location.href = url;
        }
    };
    mg.GetDecimalLength = function (d) {
        var num = (typeof (d) == "string" ? parseFloat(d) : d);
        if (isNaN(num)) {
            return 0;
        }

        var str = num.toString();
        var index = str.indexOf(".");
        return (index == -1 ? 0 : str.length - index - 1);
    };
    mg.Round = function (d, decimals) {
        var num = (typeof (d) == "string" ? parseFloat(d) : d);
        if (isNaN(num)) {
            return 0;
        }

        var multiple = Math.pow(10, decimals);
        return Math.round(num * multiple) / multiple;
    };
    mg.ConvertToAmount = function (d, decimals) {
        var str = d.toString();
        var dotIndex = str.indexOf(".");
        if (dotIndex == -1) {
            str += ".";
            for (var i = 0; i < decimals; i++) {
                str += "0";
            }
            return str;
        }
        else {
            var decLength = decimals - (str.length - dotIndex - 1);
            if (decLength > 0) {
                for (var i = 0; i < decLength; i++) {
                    str += "0";
                }
            }
            return str;
        }
    };
    mg.Random = function (minValue, maxValue) {
        var num = maxValue - minValue;
        if (num < 0) {
            throw new error("参数异常：随机数范围的最大值未超过最小值！");
        }
        if (num == 0) {
            return minValue;
        }
        return Math.random() * num + minValue;
    };
    mg.EqualOrContains = function (container, contained) {
        return container == contained || $.contains(container, contained);
    };
    return mg;
} (jQuery, MG || {}));
//#endregion

//分页加载列表
(function ($, $$) {
    function AsyncResult(deferred) {
        var _deferred = deferred;

        this.fail = function (data) {
            _deferred.reject(data);
        };

        this.done = function (data) {
            _deferred.resolve(data);
        };

        return this;
    };

    function PagingLoader(opts) {
        var _this = this;
        var _zContainer;
        var _jqContainer, _jqList;
        var _pageSize, _pageIndex = 0, _pageCount = 0, _totalRecordCount = 0;
        var _targetIndex = 0;
        var _loading = false;

        this.options = {
            pageSize: 5,
            containerSelector: ".paging-container",
            listSelector: ".paging-list",
            loadData: function (args) { },
            render: function (data, jqList, jqContainer) { },
            renderEmpty: function (jqList, jqContainer) { },
            renderEnd: function (jqList, jqContainer) { }
        };

        this.init = function () {
            $$.extend(this.options, opts);
            _pageSize = this.options.pageSize;
            _zContainer = $(this.options.containerSelector);
            _jqContainer = $$(this.options.containerSelector);
            _jqList = _jqContainer.find(this.options.listSelector);

            //无限加载
            $(document).on("infinite", ".infinite-scroll", function () { _loadAsync(); });

            //下拉刷新
            $(document).on("refresh", ".pull-to-refresh-content", function (e) { _refreshAsync(); });

            //初始加载
            _refreshAsync();
        };

        function _render(data) {
            if (data == null || data.records == null || !(data.records instanceof Array) || data.records.length == 0) {
                _renderEnd();
            }
            else {
                if (_this.options.render != null) {
                    _this.options.render.call(_this, data, _jqList, _jqContainer);
                }
                if (_isEnd()) {
                    _renderEnd();
                }
            }
        }

        function _renderEmpty() {
            $.detachInfiniteScroll(_zContainer);
            _jqContainer.find(".infinite-scroll-preloader").hide();

            if (_this.options.renderEmpty != null) {
                _this.options.renderEmpty.call(_this, _jqList, _jqContainer);
            }
        }

        function _renderEnd() {
            $.detachInfiniteScroll(_zContainer);
            _jqContainer.find(".infinite-scroll-preloader").hide();

            if (_this.options.renderEnd != null) {
                _this.options.renderEnd.call(_this, _jqList, _jqContainer);
            }
        }

        function _resetCount(data) {
            if (data == null || data.totalRecordCount == null || isNaN(Number(data.totalRecordCount))) {
                _totalRecordCount = 0;
                _pageCount = 0;
            }
            else {
                _totalRecordCount = Number(data.totalRecordCount);
                _pageCount = Math.ceil(_totalRecordCount / _pageSize);
            }
        }

        function _refreshAsync() {
            _targetIndex = 0;

            return _getData("refresh").done(_refreshSuccess).always(_refreshComplete);
        };

        function _refreshSuccess(data) {
            _pageIndex = 0;
            _resetCount(data);
            _jqList.empty();
            if (_totalRecordCount == 0) {
                _renderEmpty();
            }
            else {
                if (!_isEnd()) {
                    $.attachInfiniteScroll(_zContainer);
                    _jqContainer.find(".infinite-scroll-preloader").show();
                }
                _render(data);
            }
        };

        function _refreshComplete() {
            $.pullToRefreshDone(_zContainer.find(".pull-to-refresh-content")); //删除刷新提示符
        };

        function _loadAsync() {
            if (_loading === false) {
                _loading = true;
                _targetIndex = _pageIndex + 1;
                return _getData("infinite").done(_loadSuccess).always(_loadCompelte);
            }
        }

        function _loadSuccess(data) {
            _pageIndex = _targetIndex;
            _render(data);
        }

        function _loadCompelte() {
            _loading = false;
        }

        function _getData(eventType) {
            var deferred = $$.Deferred();
            var args = {
                pageIndex: _targetIndex,
                pageSize: _pageSize,
                eventType: eventType,
                ar: new AsyncResult(deferred)
            };
            _this.options.loadData(args);
            return deferred;
        };

        function _isEnd() {
            if (_pageCount > 0) {
                return _pageIndex == (_pageCount - 1);
            }
            return true;
        }

        this.getIndex = function () { return _pageIndex; };

        this.getPageCount = function () { return _pageCount; };

        return this;
    };

    $$.initPagingLoader = function (opts) {
        new PagingLoader(opts).init();
    };
})(Zepto, jQuery);